<template>
  <div class="analytics-page">
    <!-- 页面标题和过滤器 -->
    <div class="page-header">
      <div class="header-left">
        <h1>数据分析中心</h1>
        <p class="subtitle">系统运行和业务数据的详细分析</p>
      </div>
      <div class="header-right">
        <el-select v-model="timeRange" placeholder="选择时间范围" size="large" class="time-range-select">
          <el-option
            v-for="item in timeRangeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-button type="primary" :icon="Refresh" @click="refreshData">刷新数据</el-button>
        <el-tooltip content="导出数据为Excel" placement="top">
          <el-button :icon="Download" @click="exportData" circle plain></el-button>
        </el-tooltip>
      </div>
    </div>

    <!-- 统计卡片行 -->
    <div class="stat-cards-row">
      <stat-card
        v-for="(card, index) in statCards"
        :key="index"
        :value="card.value"
        :label="card.label"
        :unit="card.unit"
        :icon="card.icon"
        :type="card.type"
        :trend="card.trend"
        :chart-data="card.chartData"
        :loading="loading"
        show-action
        @action="handleCardAction(card)"
      />
    </div>

    <!-- 主要趋势图表 -->
    <el-card class="main-chart-card" shadow="hover">
      <template #header>
        <div class="chart-card-header">
          <h3>系统性能趋势</h3>
          <div class="chart-controls">
            <el-radio-group v-model="selectedMetric" size="small">
              <el-radio-button v-for="metric in metrics" :key="metric.value" :label="metric.value">
                {{ metric.label }}
              </el-radio-button>
            </el-radio-group>
          </div>
        </div>
      </template>
      <div class="chart-loading-container" v-if="loading">
        <el-skeleton animated :rows="6" />
      </div>
      <base-chart 
        v-else
        :option="trendChartOption" 
        height="400px"
        @click="handleChartClick"
      />
    </el-card>

    <!-- 数据分析卡片行 -->
    <div class="data-analysis-row">
      <!-- 用户分布卡片 -->
      <el-card class="analysis-card" shadow="hover">
        <template #header>
          <div class="chart-card-header">
            <h3>用户地域分布</h3>
            <el-select v-model="userDistType" size="small" style="width: 120px">
              <el-option label="省份" value="province" />
              <el-option label="城市" value="city" />
              <el-option label="终端类型" value="device" />
            </el-select>
          </div>
        </template>
        <div class="chart-loading-container" v-if="loading">
          <el-skeleton animated :rows="3" />
        </div>
        <base-chart 
          v-else 
          :option="userDistributionChartOption" 
          height="300px"
        />
      </el-card>

      <!-- 转化漏斗卡片 -->
      <el-card class="analysis-card" shadow="hover">
        <template #header>
          <div class="chart-card-header">
            <h3>业务转化漏斗</h3>
            <el-tooltip content="访问-注册-激活-付费转化漏斗" placement="top">
              <el-icon class="info-icon"><InfoFilled /></el-icon>
            </el-tooltip>
          </div>
        </template>
        <div class="chart-loading-container" v-if="loading">
          <el-skeleton animated :rows="3" />
        </div>
        <base-chart 
          v-else 
          :option="funnelChartOption" 
          height="300px"
        />
      </el-card>
    </div>

    <!-- 详细数据表格 -->
    <el-card class="data-table-card" shadow="hover">
      <template #header>
        <div class="chart-card-header">
          <h3>详细指标数据</h3>
          <div class="table-controls">
            <el-input
              v-model="searchQuery"
              placeholder="搜索..."
              prefix-icon="Search"
              size="small"
              style="width: 200px; margin-right: 10px"
            />
            <el-select v-model="tableFilterType" size="small" style="width: 120px">
              <el-option label="全部指标" value="all" />
              <el-option label="重点关注" value="important" />
              <el-option label="异常数据" value="anomaly" />
            </el-select>
          </div>
        </div>
      </template>
      <el-table
        v-loading="loading"
        :data="filteredTableData"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="date" label="日期" width="120" sortable />
        <el-table-column prop="name" label="指标名称" width="160" />
        <el-table-column prop="value" label="数值" width="100" sortable>
          <template #default="scope">
            {{ formatNumberWithCommas(scope.row.value) }}
          </template>
        </el-table-column>
        <el-table-column prop="ratio" label="环比" width="100" sortable>
          <template #default="scope">
            <span :class="getRatioClass(scope.row.ratio)">
              {{ formatRatio(scope.row.ratio) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="target" label="目标值" width="100" sortable>
          <template #default="scope">
            {{ formatNumberWithCommas(scope.row.target) }}
          </template>
        </el-table-column>
        <el-table-column prop="achievement" label="达成率" width="120" sortable>
          <template #default="scope">
            <el-progress
              :percentage="scope.row.achievement"
              :status="getProgressStatus(scope.row.achievement)"
              :stroke-width="8"
            />
          </template>
        </el-table-column>
        <el-table-column prop="trend" label="趋势" min-width="180">
          <template #default="scope">
            <div class="mini-chart" v-if="!loading">
              <base-chart
                :option="getMiniChartOption(scope.row.trend)"
                height="30px"
                :auto-resize="true"
              />
            </div>
            <div v-else class="mini-chart-loading"></div>
          </template>
        </el-table-column>
      </el-table>
      <div class="table-pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.length"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch, nextTick } from 'vue'
import { 
  TrendCharts, Refresh, Download, Search, InfoFilled, 
  DataAnalysis, Timer, User, Money, ShoppingCart, Platform, Promotion
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import BaseChart from '@/components/charts/BaseChart.vue'
import StatCard from '@/components/charts/StatCard.vue'

// 页面状态
const loading = ref(false)
const timeRange = ref('7days')
const timeRangeOptions = [
  { value: 'today', label: '今日' },
  { value: 'yesterday', label: '昨日' },
  { value: '7days', label: '近7天' },
  { value: '30days', label: '近30天' },
  { value: '90days', label: '近90天' },
  { value: 'custom', label: '自定义' }
]

// 选择的指标
const selectedMetric = ref('visits')
const metrics = [
  { value: 'visits', label: '访问量' },
  { value: 'users', label: '用户数' },
  { value: 'conversions', label: '转化率' },
  { value: 'revenue', label: '营收' }
]

// 用户分布类型
const userDistType = ref('province')

// 表格状态
const searchQuery = ref('')
const tableFilterType = ref('all')
const currentPage = ref(1)
const pageSize = ref(10)

// 模拟数据 - 统计卡片
const statCards = [
  {
    value: 25764,
    label: '日访问量',
    icon: Platform,
    type: 'primary',
    trend: { type: 'up', value: 12.5 },
    chartData: [120, 132, 101, 134, 90, 230, 210]
  },
  {
    value: 1284,
    label: '新增用户',
    icon: User,
    type: 'success',
    trend: { type: 'up', value: 5.2 },
    chartData: [220, 182, 191, 234, 290, 330, 310]
  },
  {
    value: 6785,
    label: '订单总数',
    icon: ShoppingCart,
    type: 'warning',
    trend: { type: 'down', value: 2.8 },
    chartData: [150, 232, 201, 154, 190, 330, 410]
  },
  {
    value: 127625,
    unit: '元',
    label: '总营收',
    icon: Money,
    type: 'danger',
    trend: { type: 'up', value: 8.9 },
    chartData: [320, 332, 301, 334, 390, 330, 320]
  }
]

// 模拟趋势数据
const generateTrendData = () => {
  const now = new Date()
  const dates = Array(30).fill(0).map((_, i) => {
    const date = new Date(now)
    date.setDate(date.getDate() - (29 - i))
    return date.toISOString().split('T')[0]
  })

  return {
    visits: dates.map(date => [date, Math.floor(Math.random() * 5000) + 20000]),
    users: dates.map(date => [date, Math.floor(Math.random() * 1000) + 800]),
    conversions: dates.map(date => [date, Math.floor(Math.random() * 20) + 10]),
    revenue: dates.map(date => [date, Math.floor(Math.random() * 50000) + 100000])
  }
}

// 趋势数据
const trendData = reactive(generateTrendData())

// 趋势图表配置
const trendChartOption = computed(() => {
  const data = trendData[selectedMetric.value]
  
  const yAxisFormatter = (value) => {
    if (selectedMetric.value === 'conversions') {
      return value + '%'
    } else if (selectedMetric.value === 'revenue') {
      return (value / 10000).toFixed(1) + '万'
    } else {
      return value
    }
  }
  
  return {
    tooltip: {
      trigger: 'axis',
      formatter: function(params) {
        const param = params[0]
        const date = param.data[0]
        const value = param.data[1]
        
        let valueDisplay = value
        if (selectedMetric.value === 'conversions') {
          valueDisplay = value + '%'
        } else if (selectedMetric.value === 'revenue') {
          valueDisplay = '¥' + value.toLocaleString()
        } else {
          valueDisplay = value.toLocaleString()
        }
        
        return `${date} <br/> ${param.seriesName}: ${valueDisplay}`
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: data.map(item => item[0]),
      axisLabel: {
        interval: 'auto',
        rotate: 30
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: yAxisFormatter
      }
    },
    series: [
      {
        name: metrics.find(m => m.value === selectedMetric.value).label,
        type: 'line',
        smooth: true,
        data: data.map(item => item[1]),
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(64, 158, 255, 0.6)' },
              { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
            ]
          }
        },
        lineStyle: {
          width: 3,
          color: '#409EFF'
        },
        itemStyle: {
          color: '#409EFF'
        },
        markPoint: {
          data: [
            { type: 'max', name: '最大值' },
            { type: 'min', name: '最小值' }
          ]
        },
        markLine: {
          data: [
            { type: 'average', name: '平均值' }
          ]
        }
      }
    ]
  }
})

// 用户分布图表配置
const userDistributionChartOption = computed(() => {
  // 根据选择的类型返回不同图表
  if (userDistType.value === 'device') {
    return {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'horizontal',
        bottom: 0
      },
      series: [
        {
          name: '设备分布',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '12',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: [
            { value: 1048, name: '移动端' },
            { value: 735, name: '桌面端' },
            { value: 580, name: '平板' },
            { value: 484, name: '微信小程序' },
            { value: 300, name: '其他' }
          ]
        }
      ]
    }
  } else {
    return {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'value',
        boundaryGap: [0, 0.01]
      },
      yAxis: {
        type: 'category',
        data: userDistType.value === 'province' 
          ? ['北京', '上海', '广东', '江苏', '浙江', '四川', '湖北', '其他']
          : ['北京', '上海', '广州', '深圳', '杭州', '南京', '成都', '其他']
      },
      series: [
        {
          name: userDistType.value === 'province' ? '省份分布' : '城市分布',
          type: 'bar',
          data: [18203, 23489, 29034, 10970, 16744, 9851, 7556, 45230],
          itemStyle: {
            color: function(params) {
              const colorList = [
                '#5470c6', '#91cc75', '#fac858', '#ee6666',
                '#73c0de', '#3ba272', '#fc8452', '#9a60b4'
              ]
              return colorList[params.dataIndex % colorList.length]
            }
          }
        }
      ]
    }
  }
})

// 转化漏斗图表配置
const funnelChartOption = computed(() => {
  return {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b} : {c}%'
    },
    legend: {
      data: ['访问', '注册', '激活', '付费', '复购'],
      bottom: 0
    },
    series: [
      {
        name: '转化率',
        type: 'funnel',
        left: '10%',
        top: 10,
        bottom: 40,
        width: '80%',
        min: 0,
        max: 100,
        minSize: '0%',
        maxSize: '100%',
        sort: 'descending',
        gap: 2,
        label: {
          show: true,
          position: 'inside'
        },
        labelLine: {
          length: 10,
          lineStyle: {
            width: 1,
            type: 'solid'
          }
        },
        itemStyle: {
          borderColor: '#fff',
          borderWidth: 1
        },
        emphasis: {
          label: {
            fontSize: 14,
            fontWeight: 'bold'
          }
        },
        data: [
          { value: 100, name: '访问' },
          { value: 68, name: '注册' },
          { value: 42, name: '激活' },
          { value: 25, name: '付费' },
          { value: 12, name: '复购' }
        ]
      }
    ]
  }
})

// 模拟表格数据
const generateTableData = () => {
  const types = ['访问量', '页面浏览', '新用户', '活跃用户', '订单数', '成交金额', '转化率', '平均停留时间', '跳出率']
  const data = []
  
  const now = new Date()
  for (let i = 0; i < 100; i++) {
    const date = new Date(now)
    date.setDate(date.getDate() - Math.floor(Math.random() * 30))
    
    const value = Math.floor(Math.random() * 10000) + 1000
    const target = Math.floor(Math.random() * 5000) + 5000
    const achievement = Math.round((value / target) * 100)
    
    data.push({
      date: date.toISOString().split('T')[0],
      name: types[Math.floor(Math.random() * types.length)],
      value: value,
      ratio: (Math.random() * 40) - 20, // -20% to +20%
      target: target,
      achievement: achievement > 100 ? 100 : achievement,
      trend: Array.from({ length: 12 }, () => Math.floor(Math.random() * 100) + 50),
      important: Math.random() > 0.7,
      anomaly: Math.random() > 0.85
    })
  }
  
  return data
}

// 表格数据
const tableData = ref(generateTableData())

// 筛选后的表格数据
const filteredTableData = computed(() => {
  let result = tableData.value.filter(row => {
    if (searchQuery.value && !row.name.includes(searchQuery.value) && 
        !row.date.includes(searchQuery.value)) {
      return false
    }
    
    if (tableFilterType.value === 'important' && !row.important) {
      return false
    }
    
    if (tableFilterType.value === 'anomaly' && !row.anomaly) {
      return false
    }
    
    return true
  })
  
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  
  return result.slice(start, end)
})

// 小型图表配置
const getMiniChartOption = (data) => {
  return {
    tooltip: { show: false },
    xAxis: {
      type: 'category',
      show: false,
      boundaryGap: false
    },
    yAxis: {
      type: 'value',
      show: false
    },
    grid: {
      top: 0,
      left: 0,
      right: 0,
      bottom: 0
    },
    series: [{
      data: data,
      type: 'line',
      smooth: true,
      symbol: 'none',
      lineStyle: {
        width: 2,
        color: '#67C23A'
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: 'rgba(103, 194, 58, 0.3)' },
            { offset: 1, color: 'rgba(103, 194, 58, 0.1)' }
          ]
        }
      }
    }]
  }
}

// 格式化数字为千分位
const formatNumberWithCommas = (number) => {
  return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")
}

// 格式化比率
const formatRatio = (ratio) => {
  const prefix = ratio > 0 ? '+' : ''
  return `${prefix}${ratio.toFixed(2)}%`
}

// 获取比率的CSS类
const getRatioClass = (ratio) => {
  if (ratio > 0) return 'ratio-up'
  if (ratio < 0) return 'ratio-down'
  return 'ratio-flat'
}

// 获取进度条状态
const getProgressStatus = (value) => {
  if (value >= 100) return 'success'
  if (value >= 80) return ''
  if (value >= 60) return 'warning'
  return 'exception'
}

// 事件处理
const refreshData = () => {
  loading.value = true
  setTimeout(() => {
    Object.assign(trendData, generateTrendData())
    tableData.value = generateTableData()
    loading.value = false
    ElMessage.success('数据已刷新')
  }, 1000)
}

const handleCardAction = (card) => {
  ElMessage.info(`查看 ${card.label} 的详细数据`)
}

const handleChartClick = (params) => {
  const date = params.name
  const value = params.value
  ElMessage.info(`您点击了日期: ${date}, 值: ${value}`)
}

const exportData = () => {
  ElMessageBox.confirm(
    '是否确认导出当前数据？',
    '导出确认',
    {
      confirmButtonText: '确认导出',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    setTimeout(() => {
      ElMessage.success('数据导出成功')
    }, 1000)
  }).catch(() => {})
}

const handleSizeChange = (val) => {
  pageSize.value = val
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 监听时间范围变化
watch(timeRange, (newVal) => {
  if (newVal === 'custom') {
    ElMessageBox.prompt(
      '请输入自定义日期范围',
      '自定义时间',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPlaceholder: '例如: 2023-01-01 至 2023-01-31'
      }
    ).then(({ value }) => {
      ElMessage.success(`已选择自定义日期: ${value}`)
      refreshData()
    }).catch(() => {
      timeRange.value = '7days'
    })
  } else {
    refreshData()
  }
})

// 初始化
onMounted(() => {
  // 延迟加载数据，确保DOM已渲染完毕
  nextTick(() => {
    setTimeout(() => {
      refreshData()
    }, 300)
  })
})
</script>

<style lang="scss" scoped>
.analytics-page {
  padding: 24px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  
  .header-left {
    h1 {
      font-size: 24px;
      font-weight: 600;
      margin: 0 0 8px 0;
      color: #303133;
    }
    
    .subtitle {
      font-size: 14px;
      color: #909399;
      margin: 0;
    }
  }
  
  .header-right {
    display: flex;
    align-items: center;
    gap: 12px;
    
    .time-range-select {
      width: 140px;
    }
  }
}

.stat-cards-row {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
  margin-bottom: 24px;
}

.main-chart-card {
  margin-bottom: 24px;
}

.data-analysis-row {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(450px, 1fr));
  gap: 16px;
  margin-bottom: 24px;
}

.chart-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  h3 {
    font-size: 16px;
    font-weight: 500;
    margin: 0;
    color: #303133;
  }
  
  .info-icon {
    font-size: 16px;
    color: #909399;
    cursor: help;
  }
}

.chart-loading-container {
  padding: 20px 0;
}

.data-table-card {
  margin-bottom: 24px;
  
  .table-controls {
    display: flex;
    align-items: center;
  }
  
  .table-pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .mini-chart {
    width: 100%;
    height: 30px;
    min-width: 120px;
  }
  
  .mini-chart-loading {
    width: 100%;
    height: 30px;
    background-color: #f5f7fa;
    border-radius: 4px;
  }
}

.ratio-up {
  color: #67C23A;
}

.ratio-down {
  color: #F56C6C;
}

.ratio-flat {
  color: #909399;
}

// 响应式调整
@media screen and (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    
    .header-right {
      margin-top: 16px;
      width: 100%;
      flex-wrap: wrap;
      
      .time-range-select {
        width: 100%;
        margin-bottom: 8px;
      }
    }
  }
  
  .stat-cards-row {
    grid-template-columns: 1fr;
  }
  
  .data-analysis-row {
    grid-template-columns: 1fr;
  }
}
</style>
